package ldh.im.rpc.connection.socket;

import ldh.im.rpc.buffer.RpcBuffer;
import ldh.im.rpc.connection.RpcReadChannel;

import java.io.IOException;
import java.net.Socket;
import java.nio.channels.ClosedChannelException;

public class RpcSocketChannel implements RpcReadChannel {

    protected Socket socket;
    protected RpcBuffer rpcBuffer;

    public RpcSocketChannel(RpcBuffer rpcBuffer, Socket socket) {
        this.rpcBuffer = rpcBuffer;
        this.socket = socket;
    }

    @Override
    public int read(int length) throws IOException {
        if (socket.isConnected()) {
            return rpcBuffer.readFromStream(socket.getInputStream(), length);
        }
        throw new ClosedChannelException();
    }
}
